<script setup lang="ts">
import { h, onMounted, ref } from 'vue'
import { getProductVoByIdUsingGet, purchaseProductUsingPost } from '@/api/productController.ts'
import { message } from 'ant-design-vue'
import { DollarOutlined, ShoppingCartOutlined } from '@ant-design/icons-vue'
import { addCartUsingPost } from '@/api/cartController.ts'
import { useRouter } from 'vue-router'

interface Props {
  id: number | string
}

const router = useRouter()

const props = defineProps<Props>()

const product = ref<API.ProductVo>({})

const getProductInfoById = async () => {
  if (!props.id) {
    return
  }
  const res = await getProductVoByIdUsingGet({
    id: props.id,
  })
  if (res.code === 200 && res.data) {
    product.value = res.data as API.ProductVo
  } else {
    message.error(res.message)
  }
}

// 加入购物车
const doAddCart = async (id: any) => {
  if (!id) {
    return
  }
  const res = await addCartUsingPost({
    productId: id,
  })
  if (res.code === 200) {
    message.success('添加成功')
    await router.push('/cart/my')
  } else {
    message.error(res.message)
  }
}

// 购买
const doPurchase = async (productId: any) => {
  if (!productId) {
    return
  }
  const res = await purchaseProductUsingPost({
    productId: productId,
  })
  if (res.code === 200) {
    message.success('购买成功')
  } else {
    message.error(res.message)
  }
}

onMounted(() => getProductInfoById())
</script>

<template>
  <div id="product-detail-view">
    <a-row :gutter="[16, 16]">
      <!-- 商品图片预览 -->
      <a-col :sm="24" :md="16" :xl="12">
        <a-card title="图片预览">
          <a-image :src="product.image" style="max-height: 600px; object-fit: contain" />
        </a-card>
      </a-col>
      <!-- 商品信息  -->
      <a-col :sm="24" :md="8" :xl="12">
        <a-card title="商品信息">
          <a-descriptions :column="1">
            <a-descriptions-item label="名称">
              {{ product.name ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="描述">
              {{ product.description ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="价格"> ¥{{ product.price ?? '-' }}</a-descriptions-item>
            <a-descriptions-item label="库存">
              {{ product.stock ?? '-' }}
            </a-descriptions-item>
          </a-descriptions>
          <!-- 图片操作 -->
          <a-space wrap>
            <a-button
              :icon="h(ShoppingCartOutlined)"
              type="primary"
              ghost
              @click="doAddCart(product.id)"
            >
              加入购物车
            </a-button>
            <a-button :icon="h(DollarOutlined)" type="default" @click="doPurchase(product.id)">
              购买
            </a-button>
          </a-space>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<style scoped></style>
